package com.qdu.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.qdu.bean.User;
import com.qdu.commons.AccessToken;
import com.qdu.util.EncryptUtil;
import com.qdu.commons.Result;
import com.qdu.service.UserService;
import com.qdu.util.JWTUtil;
import com.qdu.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;

    @Autowired
    RedisUtil redisUtil;

    private static final String METHOD = "OPTIONS";
    private static final String TOKEN = "token";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();

        if (StringUtils.equalsIgnoreCase(METHOD, method)) {
            log.info("放行 -{}",method);
            return true;
        }

        String token = request.getHeader("token");
        String username = JWTUtil.getUsername(token);
        long time = System.currentTimeMillis();
        String newToken= JWTUtil.createToken(username,time);
        redisUtil.set(username,time,60*30);
        response.setHeader("token", newToken);



        return true;
    }

    /**
     * 返回没有权限
     *
     * @param response
     */
    public void noAuth(HttpServletResponse response,String msg) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Result result = Result.noAuth(msg);
        String json = JSONObject.toJSONString(result);
        log.info("json -{}",json);
        writer.print(json);
        writer.flush();
        writer.close();
    }


}
